package com.recorder.recorder_lib;

import android.media.MediaPlayer;

/**
 * desc   :
 * author : guowenlong
 * Email  : guowenlong20000@gmail.com
 * time   : 2018年12月21日18 : 05
 */
public class PlayManager {
    private MediaPlayer mMediaPlayer;
    private static PlayManager instance;

    public synchronized static PlayManager getInstance() {
        if (instance == null) {
            instance = new PlayManager();
        }
        return instance;
    }

    public void playSound(String url) {
        if (mMediaPlayer != null) {
            stopSound();
        }
        mMediaPlayer = new MediaPlayer();
        try {
            mMediaPlayer.setDataSource(url);
            mMediaPlayer.prepareAsync();
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mMediaPlayer.start();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stopSound() {
        if (mMediaPlayer == null)
            return;
        try {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }
}
